var App = angular.module('angle', [
    'ngRoute',
  'ngAnimate',
   // 'ngStorage',
  //  'ngCookies',
   // 'pascalprecht.translate',
    'ui.bootstrap',
    'ui.router',
    'oc.lazyLoad',
    'cfp.loadingBar',
   // 'ngSanitize',
  //  'ngResource',
  //  'tmh.dynamicLocale',
   // 'ui.utils',
    'angular.filter',
    'angular-loading-bar',
  'treasure-overlay-spinner',
'infinite-scroll'//分页加载
    //'RecursionHelper'

   // 'ngTouch'
]);
run.$inject = ['$rootScope'];
function run($rootScope) {
    $rootScope.spinner = {
        active: false,
        on: function () {
            this.active = true;
        },
        off: function () {
            this.active = false;
        }
    };
}
App.run(run);
App.run(["$rootScope", "$state", "$stateParams", '$window', '$templateCache', '$http', '$filter', '$location', '$timeout',
    function ($rootScope, $state, $stateParams, $window, $templateCache, $http, $filter, $location, $timeout) {
        // Set reference to access them from any scope
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
        $rootScope.$storage = $window.localStorage;
        //  $rootScope.metabcy = "width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=0";

        // Uncomment this to disable template cache
        //$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        //    if (typeof(toState) !== 'undefined'){
        //      $templateCache.remove(toState.templateUrl);
        //    }
        //});
        $rootScope.GoBack = function () {
            window.history.back();
        };
        $rootScope.KeepScroll = function (css) {
            var hp = parseInt($rootScope.scrollPos[$location.path()] ? $rootScope.scrollPos[$location.path()] : 0);
            var wh = $(window).height();
            $(css).css("min-height", hp + wh);
            window.scrollTo(0, hp);
            $rootScope.okSaveScroll = true;
        }
        //$rootScope.ImgUploadUrl = "http://file.xsmore.com/api/image/upload";
        //$rootScope.$on('$viewContentLoaded', function () {
        //    $templateCache.removeAll();
        //});

        // Scope Globals
        // ----------------------------------- 
        $rootScope.app = {
            name: '优品三悦',
            description: '社交购物',
            year: ((new Date()).getFullYear()),
            layout: {
                isFixed: true,
                isCollapsed: false,
                isBoxed: false,
                isRTL: false,
                horizontal: false,
                isFloat: false,
                asideHover: false,
                theme: null
            },
            useFullLayout: false,
            hiddenFooter: false,
            viewAnimation: 'ng-fadeInUp',
            isweixin: $window.navigator.userAgent.indexOf('MicroMessenger') > -1

        };


        $rootScope.WxConfig = function (url) {
            $http.post('/Wx/JsSdkConfig', { url: url }).success(function (response) {
                var d = {
                    debug: false,
                    appId: response.appid,
                    timestamp: response.timestamp,
                    nonceStr: response.nonceStr,
                    signature: response.signature,
                    jsApiList: response.jsApiList
                };
                wx.config(
                   {
                       debug: false,
                       appId: response.appid,
                       timestamp: response.timestamp,
                       nonceStr: response.nonceStr,
                       signature: response.signature,
                       jsApiList: response.jsApiList
                   }
                );
            });
        }



        $rootScope.WxShare = function (title, desc, url, imgurl, suc, can) {
            wx.ready(function () {
                //wx.error(function (res) {
                //    alert(JSON.stringify(res));
                //});
                var shareData = {
                    title: title, // 分享标题
                    desc: desc, // 分享语
                    link: url, // 分享链接
                    imgUrl: imgurl,
                    success: suc,
                    cancel: can
                };
                wx.showOptionMenu();
                wx.onMenuShareTimeline(shareData);
                wx.onMenuShareAppMessage(shareData);
                wx.onMenuShareWeibo(shareData);
                wx.onMenuShareQQ(shareData);
                wx.onMenuShareQZone(shareData);
            });
        }
        //$timeout(function () { $rootScope.WxConfig(encodeURIComponent(location.href.split('#')[0])); }, 1000);
        $rootScope.WxConfig(encodeURIComponent(location.href));


        //内外网网址分开
        $rootScope.WxShare2 = function (title, desc, url1, url2, imgurl, suc, can) {
            wx.ready(function () {
                //wx.error(function (res) {
                //    alert(JSON.stringify(res));
                //});
                var shareData1 = {
                    title: title, // 分享标题
                    desc: desc, // 分享语
                    link: url1, // 分享链接
                    imgUrl: imgurl,
                    success: suc,
                    cancel: can
                };
                var shareData2 = {
                    title: title, // 分享标题
                    desc: desc, // 分享语
                    link: url2, // 分享链接
                    imgUrl: imgurl,
                    success: suc,
                    cancel: can
                };
                wx.showOptionMenu();
                wx.onMenuShareTimeline(shareData1);
                wx.onMenuShareAppMessage(shareData1);
                wx.onMenuShareWeibo(shareData2);
                wx.onMenuShareQQ(shareData2);
                wx.onMenuShareQZone(shareData2);
            });
        }

        $rootScope.sum = function (items, prop) {
            if (items == null) {
                return 0;
            }
            return items.reduce(function (a, b) {
                return b[prop] == null ? a : a + parseFloat(b[prop]);
            }, 0);
        };





        $rootScope.ShortP = function (name) {
            if (name === "内蒙古自治区" || name === "黑龙江省") {
                name = name.substring(0, 3);
            }
            else
                name = name.substring(0, 2);
            return name;
        }


        $rootScope.NumDx = function numtochinese(num) {
            var currencyDigits = num.toString();

            var MAXIMUM_NUMBER = 99999999999.99;  //最大值
            // 定义转移字符
            var CN_ZERO = "零";
            var CN_ONE = "壹";
            var CN_TWO = "贰";
            var CN_THREE = "叁";
            var CN_FOUR = "肆";
            var CN_FIVE = "伍";
            var CN_SIX = "陆";
            var CN_SEVEN = "柒";
            var CN_EIGHT = "捌";
            var CN_NINE = "玖";
            var CN_TEN = "拾";
            var CN_HUNDRED = "佰";
            var CN_THOUSAND = "仟";
            var CN_TEN_THOUSAND = "万";
            var CN_HUNDRED_MILLION = "亿";
            var CN_DOLLAR = "元";
            var CN_TEN_CENT = "角";
            var CN_CENT = "分";
            var CN_INTEGER = "整";

            // 初始化验证:
            var integral, decimal, outputCharacters, parts;
            var digits, radices, bigRadices, decimals;
            var zeroCount;
            var i, p, d;
            var quotient, modulus;

            currencyDigits = currencyDigits.replace(/,/g, "");
            currencyDigits = currencyDigits.replace(/^0+/, "");


            parts = currencyDigits.split(".");
            if (parts.length > 1) {
                integral = parts[0];
                decimal = parts[1];
                decimal = decimal.substr(0, 2);
            }
            else {
                integral = parts[0];
                decimal = "";
            }
            // 实例化字符大写人民币汉字对应的数字
            digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
            radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
            bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
            decimals = new Array(CN_TEN_CENT, CN_CENT);

            outputCharacters = "";
            //大于零处理逻辑
            if (Number(integral) > 0) {
                zeroCount = 0;
                for (i = 0; i < integral.length; i++) {
                    p = integral.length - i - 1;
                    d = integral.substr(i, 1);
                    quotient = p / 4;
                    modulus = p % 4;
                    if (d == "0") {
                        zeroCount++;
                    }
                    else {
                        if (zeroCount > 0) {
                            outputCharacters += digits[0];
                        }
                        zeroCount = 0;
                        outputCharacters += digits[Number(d)] + radices[modulus];
                    }
                    if (modulus == 0 && zeroCount < 4) {
                        outputCharacters += bigRadices[quotient];
                    }
                }
                outputCharacters += CN_DOLLAR;
            }
            // 包含小数部分处理逻辑
            if (decimal != "") {
                for (i = 0; i < decimal.length; i++) {
                    d = decimal.substr(i, 1);
                    if (d != "0") {
                        outputCharacters += digits[Number(d)] + decimals[i];
                    }
                }
            }
            //确认并返回最终的输出字符串
            if (outputCharacters == "") {
                outputCharacters = CN_ZERO + CN_DOLLAR;
            }
            if (decimal == "") {
                outputCharacters += CN_INTEGER;
            }
            return outputCharacters;
        };
        $rootScope.shortDate = function (d) {
            var dd = new Date(d);
            return $filter('date')(dd, 'yyyy-MM-dd');
        };
        $rootScope.date = function () {
            var dd = new Date();
            return $filter('date')(dd, 'yyyy-MM-dd');
        };
        //$rootScope.ImgUploadUrl = "http://file.0519see.com/api/image/upload";
        //$rootScope.ImgHostUrl = "http://file.0519see.com/ImgFile/wsd";
        $rootScope.LogoUrl = 'http://wx.youpinsanyue.com/Content/images/logo.jpg';
        $http.post('/Wx/GetAppSetting').then(function (response) {
            $rootScope.ImgUploadUrl = response.data.ImgUploadUrl;
            $rootScope.ImgHostUrl = response.data.ImgHostUrl;
        });

    }]);
App.config(function ($provide) {
    $provide.decorator("$exceptionHandler", function ($delegate) {
        return function (exception, cause) {
            //   console.log(exception);
            $delegate(exception, cause);
            //    throw exception;
        };
    });
});
App.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}]);
App.filter("jsDate", function () {
    return function (x) {
        if (null == x) {
            return null;
        }
        else {
            return new Date(parseInt(x.substr(6)));
        }
    };
});
App.config(
    function ($httpProvider) {
        $httpProvider.interceptors.push(function ($timeout, $q, $injector, $window) {
            var $http, $state, $location;
            $timeout(function () {

                $http = $injector.get('$http');
                $state = $injector.get('$state');
                $location = $injector.get('$location');
            });
            return {
                'requestError': function (rejection) {
                    // handle same as below
                },

                'responseError': function (rejection) {
                    console.log(rejection.status);
                    if (rejection.status === 406) {
                        if ($state != undefined && $state.current.name !== "shop.callback") {
                            console.log($state);
                            //本地测试直接callback
                            $state.go("shop.callback", { returnUrl: encodeURIComponent($location.absUrl()) });

                            //$state.go("shop.wx", { returnUrl: encodeURIComponent($location.absUrl()) });
                            //$window.location.replace("/Wx/Callback?returnUrl=" +
                            //         encodeURIComponent($location.absUrl()));
                        } else {
                            return $q.reject(rejection);
                        }
                    }
                    //else if (rejection.status === 401) {
                    //    if ($state.current.name !== "login") {
                    //        var userAgent = $window.navigator.userAgent;


                    //        if (userAgent.indexOf("MicroMessenger") > -1) {
                    //            $window.location.replace("/auth/weixin?redirect=" +
                    //                encodeURIComponent($location.absUrl()));
                    //        } else {
                    //            //   var r = encodeURIComponent("#" + $location.url());
                    //            //   window.location.replace("/#/login/?redirect=" + r);
                    //            $state.go("login", { redirect: "#" + $location.url() }, { location: 'replace' });
                    //        }
                    //    } else {
                    //        return $q.reject(rejection);
                    //    }

                    //    //   $state.go("/auth", { provider: 'weixin' });
                    //} else if (rejection.status === 403) {
                    //    return $q.reject(rejection);
                    //} else {

                    //    //     $state.transitionTo('404');
                    //}
                    return $q.reject(rejection);
                },
                'response': function (response) {
                    if (response.data.ErrorCode === '' || response.data.ErrorCode === '500') {
                        //  alert(response.data.Message);
                        //  return $q.reject(response);
                        $state.go('message', { msg: response.data.Message }, { location: 'replace' });
                        //  $state.go('message', { msg: response.data.Message });
                    } else if (response.data.ErrorCode && response.data.ErrorCode !== '') {
                        return $q.reject(response);
                    }
                    return response;
                }
            };
        });
    });
//App.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

//    //..省略代码
//    $locationProvider.html5Mode(true);
//}]);

App.config([
    '$ocLazyLoadProvider', 'APP_REQUIRES', function ($ocLazyLoadProvider, APP_REQUIRES) {
        'use strict';

        // Lazy Load modules configuration
        $ocLazyLoadProvider.config({
            debug: false,
            events: true,
            modules: APP_REQUIRES.modules
        });

    }
]).config([
    '$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
    function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
        'use strict';
        // registering components after bootstrap
        App.controller = $controllerProvider.register;
        App.directive = $compileProvider.directive;
        App.filter = $filterProvider.register;
        App.factory = $provide.factory;
        App.service = $provide.service;
        App.constant = $provide.constant;
        App.value = $provide.value;

    }
])
    .config([
    'cfpLoadingBarProvider', function (cfpLoadingBarProvider) {

        cfpLoadingBarProvider.includeBar = true;
        cfpLoadingBarProvider.includeSpinner = false;
        cfpLoadingBarProvider.latencyThreshold = 300;
        cfpLoadingBarProvider.parentSelector = '.wrapper > section';

    }
    ])
;

App.provider('RouteHelpers', ['APP_REQUIRES', function (appRequires) {
    "use strict";

    // Set here the base of the relative path
    // for all app views
    this.basepath = function (uri) {
        return '/pages/' + uri;
    };

    // Generates a resolve object by passing script names
    // previously configured in constant.APP_REQUIRES
    this.resolveFor = function () {
        var _args = arguments;
        return {
            deps: ['$ocLazyLoad', '$q', function ($ocLL, $q) {
                // Creates a promise chain for each argument
                var promise = $q.when(1); // empty promise
                for (var i = 0, len = _args.length; i < len; i++) {
                    promise = andThen(_args[i]);
                }
                return promise;

                // creates promise to chain dynamically
                function andThen(_arg) {
                    // also support a function that returns a promise
                    if (typeof _arg == 'function')
                        return promise.then(_arg);
                    else
                        return promise.then(function () {
                            // if is a module, pass the name. If not, pass the array
                            var whatToLoad = getRequired(_arg);
                            // simple error check
                            if (!whatToLoad) return $.error('Route resolve: Bad resource name [' + _arg + ']');
                            // finally, return a promise
                            return $ocLL.load(whatToLoad);
                        });
                }
                // check and returns required data
                // analyze module items with the form [name: '', files: []]
                // and also simple array of script files (for not angular js)
                function getRequired(name) {
                    if (appRequires.modules)
                        for (var m in appRequires.modules)
                            if (appRequires.modules[m].name && appRequires.modules[m].name === name)
                                return appRequires.modules[m];
                    return appRequires.scripts && appRequires.scripts[name];
                }

            }]
        };
    }; // resolveFor

    // not necessary, only used in config block for routes
    this.$get = function () {
        return {
            basepath: this.basepath
        }
    };

}]);


App.controller('ShopController',
  ['$rootScope', '$scope', '$state', '$window', '$timeout', 'cfpLoadingBar', '$location', '$compile', '$http',
  function ($rootScope, $scope, $state, $window, $timeout, cfpLoadingBar, $location, $compile, $http) {
      "use strict";
      $rootScope.scrollPos = {}; // scroll position of each view

      $(window).on('scroll', function () {
          if ($rootScope.okSaveScroll) { // false between $routeChangeStart and $routeChangeSuccess
              $rootScope.scrollPos[$location.path()] = $(window).scrollTop();
              //console.log($scope.scrollPos);
          }
      });

      $rootScope.scrollClear = function (path) {
          $rootScope.scrollPos[path] = 0;
      }

      // Loading bar transition
      // ----------------------------------- 
      var thBar;
      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
          $rootScope.okSaveScroll = false;
          if ($('.wrapper > section').length) // check if bar container exists
              thBar = $timeout(function () {
                  cfpLoadingBar.start();
              }, 0); // sets a latency Threshold        
          //document.querySelector("head").innerHTML = metas;
          //$rootScope.metabcy = "width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=0";
      });
      $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
          //$timeout(function () { // wait for DOM, then restore scroll position
          //    console.log($location.path());
          //    console.log($scope.scrollPos[$location.path()]);
          $rootScope.currTitle = $state.current.title;
          $rootScope.lashState = fromState;
          //}, 0);
          event.targetScope.$watch("$viewContentLoaded", function () {
              $timeout.cancel(thBar);
              cfpLoadingBar.complete();
          });
          if (toState.name.indexOf('shop.') > -1 && toState.data && !toState.data.noshare) {
              if ($rootScope.app && $rootScope.app.IsOpen === false) {
                  $state.go('message', { msg: '店铺关张中..... ' }, { location: 'replace' });
              }
              //  wx.ready(function () {
              //wx.showOptionMenu();
              // })
          } else {
              //  wx.ready(function () {
              //  wx.hideOptionMenu();
              // })
          }
      });


      // Hook not found
      $rootScope.$on('$stateNotFound',
        function (event, unfoundState, fromState, fromParams) {
            //  console.log(unfoundState.to); // "lazy.state"
            // console.log(unfoundState.toParams); // {a:1, b:2}
            // console.log(unfoundState.options); // {inherit:false} + default options
        });
      // Hook error
      $rootScope.$on('$stateChangeError',
        function (event, toState, toParams, fromState, fromParams, error) {
            console.log(error);
        });

      var currstate = $state;


      //$rootScope.currTitle = $state.current.title;
      $rootScope.pageTitle = function () {
          var title = $rootScope.app.name + ' - ' + ($rootScope.currTitle || $rootScope.app.description);
          document.title = title;
          return title;
      };
      //  $scope.colorByName = colors.byName;

      // Hides/show user avatar on sidebar
      $scope.toggleUserBlock = function () {
          $scope.$broadcast('toggleUserBlock');
      };

      $scope.gopage = function (url) {
          $state.go(url);
      }





      // cancel click event easily
      $rootScope.cancel = function ($event) {
          $event.stopPropagation();
      };

      $rootScope.geturl = function () {
          var options = {
              padding: 10,   //二维码四边空白，默认为10px
              width: 256,  //二维码图片宽度，默认为256px
              height: 256,  //二维码图片高度，默认为256px
              correctLevel: QRErrorCorrectLevel.L,    //二维码容错level，默认为高
              background: "#ffffff",    //二维码颜色
              foreground: "#000000"     //二维码背景颜色
          }
          var imgBase64 = jrQrcode.getQrBase64($location.absUrl(), options);
          return imgBase64;
          //var url = "http://qr.liantu.com/api.php?text=" + encodeURIComponent($location.absUrl());
          //return url;

      }
      $rootScope.GetBase64 = function (url) {

      }


  }]);



App.filter('propsFilter', function () {
    return function (items, props) {
        var out = [];

        if (angular.isArray(items)) {
            items.forEach(function (item) {
                var itemMatches = false;

                var keys = Object.keys(props);
                for (var i = 0; i < keys.length; i++) {
                    var prop = keys[i];
                    var text = props[prop].toLowerCase();
                    if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
                        itemMatches = true;
                        break;
                    }
                }

                if (itemMatches) {
                    out.push(item);
                }
            });
        } else {
            // Let the output be the input untouched
            out = items;
        }

        return out;
    };
});


App.directive('ngClickD', function ($rootScope) {
    return {
        scope: {
            ngClickD: '&'
        },
        link: function (scope, iElement, iAttrs) {
            iElement.bind('click', function () {
                if (iElement.attr('running') === 'running') {
                    return;
                }
                $rootScope.spinner.on();
                $rootScope.tospinner = true;
                iElement.attr('running', 'running');
                try {
                    scope.ngClickD()
                        .finally(function () {
                            $rootScope.spinner.off();
                            $rootScope.tospinner = false;
                            iElement.removeAttr('running');

                        });
                } catch (e) {
                    $rootScope.spinner.off();
                    $rootScope.tospinner = false;
                    iElement.removeAttr('running');

                } finally {

                }


            });
        }
    };
});
App.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.myEnter);
                });

                event.preventDefault();
            }
        });
    };
});
//默认图片
App.directive('nullSrc', function ($rootScope) {
    var nullSrc = {
        link: function postLink(scope, iElement, iAttrs) {
            var src = iAttrs.nullSrc ? iAttrs.nullSrc : "http://cdn.xsmore.com/Images/zmkm/class.png";
            iElement.bind('error', function () {
                angular.element(this).attr("src", src);
            });
        }
    }
    return nullSrc;
});

App.directive('back', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            elem.bind('click', function () {
                $window.history.back();
            });
        }
    };
}]);
App.directive("ngNulldata",
    function () {
        return {
            scope: {
                datasource: '=datasource'
            },
            link: function (scope, element, attrs) {
                scope.$watch('datasource',

                    function (newVal, oldValue) {
                        if (scope.datasource.length === 0) {
                            element.html('<div class=\"zmkm-nodata\">' +
                                '<img src="http://cdn.xsmore.com/Images/zmkm/wujieguo.png">' +
                                '<p class="zmkm-nodata-txt">暂无数据</p>' +
                                '</div>');
                        }
                    });
            }

        };
    });
App.directive('ngClickD2', function ($parse) {
    return {
        restrict: 'A',
        compile: function ($element, attr) {
            var fn = $parse(attr.disableOnPromise);
            return function clickHandler(scope, element, attrs) {
                element.on('click', function (event) {
                    $element.addClass('disabled');
                    scope.$apply(function () {
                        if (event) {
                            fn(scope, { $event: event }).finally(function () {
                                $element.removeClass('disabled');
                            });
                        } else {
                            $element.removeClass('disabled');
                        }
                    });
                });
            };
        }
    };
});



App.factory('RedditWithFunc', function ($http) {
    var RedditWithFunc = function (data, fun, url) {
        this.busy = false;
        this.after = '';
        this.requestData = data;
        this.requestData.skip = 0;
        this.requestData.take = data.Take;
        if (!this.requestData.Take) {
            this.requestData.Take = 20;
        }
        this.all = false;
        this.loadinfo = fun;
        this.url = url;
    };

    RedditWithFunc.prototype.nextPage = function () {
        if (this.busy) return;
        if (this.all) {
            return;
        }
        this.busy = true;
        $http.post(this.url, this.requestData).success(function (response) {
            if (!this.items) {
                this.items = [];
            }
            var items = response.ModelList.Results;
            for (var i = 0; i < items.length; i++) {
                this.items.push(items[i]);
            }
            this.requestData.skip = this.items.length;
            this.busy = false;
            this.all = items.length < this.requestData.Take || items.length === response.ModelList.Total;
            this.loadinfo(response);
        }.bind(this));
    };
    return RedditWithFunc;
});


App.factory('Reddit',
    function ($http) {
        var Reddit = function (url, data, callback) {

            //  this.items = [];
            this.busy = false;
            this.after = '';
            this.requestData = data;
            this.requestData.skip = 0;
            if (!this.requestData.Take) {
                this.requestData.Take = 10;
            }
            this.all = false;
            if (callback) {
                this.callBack = callback;
            }
            this.total = 0;
            this.url = url;
        };

        Reddit.prototype.nextPage = function (stop) {
            if (stop) {
                return;
            }
            if (this.busy) return;
            if (this.all) {
                return;
            }
            this.busy = true;
            $http.post(this.url, this.requestData)
                .success(function (response) {
                    if (!this.items) {
                        this.items = [];
                    }
                    var items = response.Results;
                    this.total = response.Total;
                    for (var i = 0; i < items.length; i++) {
                        this.items.push(items[i]);
                    }
                    if (this.items.length == 0) {
                        this.nodata = true;
                    }
                    this.requestData.skip = this.items.length;
                    this.busy = false;
                    if (response.Total) {
                        this.all = this.requestData.skip >= response.Total;
                    } else {
                        this.all = items.length < this.requestData.Take || items.length === this.total;
                    }
                    if (this.callBack) {
                        this.callBack(response);
                    }
                }.bind(this));
        };

        return Reddit;
    });


App.factory('ImageUpload', function ($http, $rootScope) {

    var ImageUpload = function (fileObj, path, maxWidth, maxHeight, quality) {
        this.fileObj = fileObj;
        this.maxWidth = maxWidth ? maxWidth : 640;
        this.maxHeight = maxHeight ? maxHeight : 1200;
        this.quality = quality ? quality : 0.8;
        this.path = path;
    }
    ImageUpload.prototype.Upload = function (callback) {

        var maxWidth = this.maxWidth;
        var maxHeight = this.maxHeight;
        var quality = this.quality;
        var path = this.path;

        var file = this.fileObj.files['0'];
        //图片方向角 added by lzk  
        var Orientation = null;

        if (file) {
            console.log("正在上传,请稍后...");
            var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式  
            if (!rFilter.test(file.type)) {
                //showMyTips("请选择jpeg、png格式的图片", false);  
                return;
            }
            // var URL = URL || webkitURL;  
            //获取照片方向角属性，用户旋转控制  
            EXIF.getData(file, function () {
                // alert(EXIF.pretty(this));  
                EXIF.getAllTags(this);
                //alert(EXIF.getTag(this, 'Orientation'));   
                Orientation = EXIF.getTag(this, 'Orientation');
                //return;  
            });

            var oReader = new FileReader();
            oReader.onload = function (e) {
                //var blob = URL.createObjectURL(file);  
                //_compress(blob, file, basePath);  
                var image = new Image();
                image.src = e.target.result;
                image.onload = function () {
                    var expectWidth = this.naturalWidth;
                    var expectHeight = this.naturalHeight;

                    if (this.naturalWidth > maxWidth) {
                        expectWidth = maxWidth;
                        expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                    } else if (this.naturalHeight > maxHeight) {
                        expectHeight = maxHeight;
                        expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                    }
                    // console.log(expectWidth + ',' + expectHeight);
                    var canvas = document.createElement("canvas");
                    var ctx = canvas.getContext("2d");
                    canvas.width = expectWidth;
                    canvas.height = expectHeight;
                    ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                    //console.log(canvas.width + ',' + canvas.height);

                    var base64 = null;
                    var mpImg = new MegaPixImage(image);
                    mpImg.render(canvas, {
                        maxWidth: maxWidth,
                        maxHeight: maxHeight,
                        quality: quality,
                        orientation: Orientation
                    });

                    base64 = canvas.toDataURL("image/jpeg", quality);



                    $http.post($rootScope.ImgUploadUrl + '?PlatForm=zmkm&Path=' + path, { Images: [base64] }).success(function (response) {

                        callback(response);


                    }).error(function () {
                        alert('上传失败')
                    });
                    //uploadImage(base64);  
                    // $("#image1").attr("src", base64);
                };
            };
            oReader.readAsDataURL(file);
        }
    }
    return ImageUpload;
})



App.directive('aDisabled', function () {
    return {
        compile: function (tElement, tAttrs, transclude) {
            //Disable ngClick
            tAttrs["ngClick"] = "!(" + tAttrs["aDisabled"] + ") && (" + tAttrs["ngClick"] + ")";

            //Toggle "disabled" to class when aDisabled becomes true
            return function (scope, iElement, iAttrs) {
                scope.$watch(iAttrs["aDisabled"], function (newValue) {
                    if (newValue !== undefined) {
                        iElement.toggleClass("disabled", newValue);
                    }
                });

                //Disable href on click
                iElement.on("click", function (e) {
                    if (scope.$eval(iAttrs["aDisabled"])) {
                        e.preventDefault();
                    }
                });
            };
        }
    };
})
App.directive(
			"bnLazySrc",
			function ($window, $document) {


			    // I manage all the images that are currently being
			    // monitored on the page for lazy loading.
			    var lazyLoader = (function () {

			        // I maintain a list of images that lazy-loading
			        // and have yet to be rendered.
			        var images = [];

			        // I define the render timer for the lazy loading
			        // images to that the DOM-querying (for offsets)
			        // is chunked in groups.
			        var renderTimer = null;
			        var renderDelay = 100;

			        // I cache the window element as a jQuery reference.
			        var win = $($window);

			        // I cache the document document height so that 
			        // we can respond to changes in the height due to
			        // dynamic content.
			        var doc = $document;
			        var documentHeight = doc.height();
			        var documentTimer = null;
			        var documentDelay = 2000;

			        // I determine if the window dimension events 
			        // (ie. resize, scroll) are currenlty being 
			        // monitored for changes.
			        var isWatchingWindow = false;


			        // ---
			        // PUBLIC METHODS.
			        // ---


			        // I start monitoring the given image for visibility
			        // and then render it when necessary.
			        function addImage(image) {

			            images.push(image);

			            if (!renderTimer) {

			                startRenderTimer();

			            }

			            if (!isWatchingWindow) {

			                startWatchingWindow();

			            }

			        }


			        // I remove the given image from the render queue.
			        function removeImage(image) {

			            // Remove the given image from the render queue.
			            for (var i = 0 ; i < images.length ; i++) {

			                if (images[i] === image) {

			                    images.splice(i, 1);
			                    break;

			                }

			            }

			            // If removing the given image has cleared the
			            // render queue, then we can stop monitoring 
			            // the window and the image queue.
			            if (!images.length) {

			                clearRenderTimer();

			                stopWatchingWindow();

			            }

			        }


			        // ---
			        // PRIVATE METHODS.
			        // ---


			        // I check the document height to see if it's changed.
			        function checkDocumentHeight() {

			            // If the render time is currently active, then 
			            // don't bother getting the document height - 
			            // it won't actually do anything.
			            if (renderTimer) {

			                return;

			            }

			            var currentDocumentHeight = doc.height();

			            // If the height has not changed, then ignore - 
			            // no more images could have come into view.
			            if (currentDocumentHeight === documentHeight) {

			                return;

			            }

			            // Cache the new document height.
			            documentHeight = currentDocumentHeight;

			            startRenderTimer();

			        }


			        // I check the lazy-load images that have yet to 
			        // be rendered. 
			        function checkImages() {

			            // Log here so we can see how often this 
			            // gets called during page activity.
			            //       console.log("Checking for visible images...");

			            var visible = [];
			            var hidden = [];

			            // Determine the window dimensions.
			            var windowHeight = win.height();
			            var scrollTop = win.scrollTop();

			            // Calculate the viewport offsets.
			            var topFoldOffset = scrollTop;
			            var bottomFoldOffset = (topFoldOffset + windowHeight);

			            // Query the DOM for layout and seperate the
			            // images into two different categories: those
			            // that are now in the viewport and those that
			            // still remain hidden.
			            for (var i = 0 ; i < images.length ; i++) {

			                var image = images[i];

			                if (image.isVisible(topFoldOffset, bottomFoldOffset)) {

			                    visible.push(image);

			                } else {

			                    hidden.push(image);

			                }

			            }

			            // Update the DOM with new image source values.
			            for (var i = 0 ; i < visible.length ; i++) {

			                visible[i].render();

			            }

			            // Keep the still-hidden images as the new 
			            // image queue to be monitored.
			            images = hidden;

			            // Clear the render timer so that it can be set
			            // again in response to window changes.
			            clearRenderTimer();

			            // If we've rendered all the images, then stop
			            // monitoring the window for changes.
			            if (!images.length) {

			                stopWatchingWindow();

			            }

			        }


			        // I clear the render timer so that we can easily 
			        // check to see if the timer is running.
			        function clearRenderTimer() {

			            clearTimeout(renderTimer);

			            renderTimer = null;

			        }


			        // I start the render time, allowing more images to
			        // be added to the images queue before the render 
			        // action is executed.
			        function startRenderTimer() {

			            renderTimer = setTimeout(checkImages, renderDelay);

			        }


			        // I start watching the window for changes in dimension.
			        function startWatchingWindow() {

			            isWatchingWindow = true;

			            // Listen for window changes.
			            win.on("resize.bnLazySrc", windowChanged);
			            win.on("scroll.bnLazySrc", windowChanged);

			            // Set up a timer to watch for document-height changes.
			            documentTimer = setInterval(checkDocumentHeight, documentDelay);

			        }


			        // I stop watching the window for changes in dimension.
			        function stopWatchingWindow() {

			            isWatchingWindow = false;

			            // Stop watching for window changes.
			            win.off("resize.bnLazySrc");
			            win.off("scroll.bnLazySrc");

			            // Stop watching for document changes.
			            clearInterval(documentTimer);

			        }


			        // I start the render time if the window changes.
			        function windowChanged() {

			            if (!renderTimer) {

			                startRenderTimer();

			            }

			        }


			        // Return the public API.
			        return ({
			            addImage: addImage,
			            removeImage: removeImage
			        });

			    })();


			    // ------------------------------------------ //
			    // ------------------------------------------ //


			    // I represent a single lazy-load image.
			    function LazyImage(element) {

			        // I am the interpolated LAZY SRC attribute of 
			        // the image as reported by AngularJS.					
			        var source = null;

			        // I determine if the image has already been 
			        // rendered (ie, that it has been exposed to the
			        // viewport and the source had been loaded).
			        var isRendered = false;

			        // I am the cached height of the element. We are 
			        // going to assume that the image doesn't change 
			        // height over time.
			        var height = null;


			        // ---
			        // PUBLIC METHODS.
			        // ---


			        // I determine if the element is above the given 
			        // fold of the page.
			        function isVisible(topFoldOffset, bottomFoldOffset) {

			            // If the element is not visible because it 
			            // is hidden, don't bother testing it.
			            if (!element.is(":visible")) {

			                return (false);

			            }

			            // If the height has not yet been calculated, 
			            // the cache it for the duration of the page.
			            if (height === null) {

			                height = element.height();

			            }

			            // Update the dimensions of the element.
			            var top = element.offset().top;
			            var bottom = (top + height);

			            // Return true if the element is:
			            // 1. The top offset is in view.
			            // 2. The bottom offset is in view.
			            // 3. The element is overlapping the viewport.
			            return (
								(
									(top <= bottomFoldOffset) &&
									(top >= topFoldOffset)
								)
							||
								(
									(bottom <= bottomFoldOffset) &&
									(bottom >= topFoldOffset)
								)
							||
								(
									(top <= topFoldOffset) &&
									(bottom >= bottomFoldOffset)
								)
						);

			        }


			        // I move the cached source into the live source.
			        function render() {

			            isRendered = true;

			            renderSource();

			        }


			        // I set the interpolated source value reported
			        // by the directive / AngularJS.
			        function setSource(newSource) {

			            source = newSource;

			            if (isRendered) {

			                renderSource();

			            }

			        }


			        // ---
			        // PRIVATE METHODS.
			        // ---


			        // I load the lazy source value into the actual 
			        // source value of the image element.
			        function renderSource() {

			            element[0].src = source;

			        }


			        // Return the public API.
			        return ({
			            isVisible: isVisible,
			            render: render,
			            setSource: setSource
			        });

			    }


			    // ------------------------------------------ //
			    // ------------------------------------------ //


			    // I bind the UI events to the scope.
			    function link($scope, element, attributes) {

			        var lazyImage = new LazyImage(element);

			        // Start watching the image for changes in its
			        // visibility.
			        lazyLoader.addImage(lazyImage);


			        // Since the lazy-src will likely need some sort
			        // of string interpolation, we don't want to 
			        attributes.$observe(
						"bnLazySrc",
						function (newSource) {

						    lazyImage.setSource(newSource);

						}
					);


			        // When the scope is destroyed, we need to remove
			        // the image from the render queue.
			        $scope.$on(
						"$destroy",
						function () {

						    lazyLoader.removeImage(lazyImage);

						}
					);

			    }


			    // Return the directive configuration.
			    return ({
			        link: link,
			        restrict: "A"
			    });

			}
		);

App.directive('numbersOnly', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            function fromUser(text) {
                if (text) {
                    var transformedInput = text.toString().replace(/[^0-9]/g, '');

                    if (transformedInput !== text) {
                        ngModelCtrl.$setViewValue(transformedInput);
                        ngModelCtrl.$render();
                    }
                    return transformedInput;
                }
                return undefined;
            }
            ngModelCtrl.$parsers.push(fromUser);
        }
    };
});
/**=========================================================
 * Module: anchor.js
 * Disables null anchor behavior
 =========================================================*/

App.directive('href', function () {

    return {
        restrict: 'A',
        compile: function (element, attr) {
            return function (scope, element) {
                if (attr.ngClick || attr.href === '' || attr.href === '#') {
                    if (!element.hasClass('dropdown-toggle'))
                        element.on('click', function (e) {
                            e.preventDefault();
                            e.stopPropagation();
                        });
                }
            };
        }
    };
});
App.directive('convertToNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function (val) {
                return parseInt(val, 10);
            });
            ngModel.$formatters.push(function (val) {
                return '' + val;
            });
        }
    };
});
/**=========================================================
 * Module: animate-enabled.js
 * Enable or disables ngAnimate for element with directive
 =========================================================*/

App.directive("animateEnabled", ["$animate", function ($animate) {
    return {
        link: function (scope, element, attrs) {
            scope.$watch(function () {
                return scope.$eval(attrs.animateEnabled, scope);
            }, function (newValue) {
                $animate.enabled(!!newValue, element);
            });
        }
    };
}]);
App.directive('goClick', function ($location) {
    return function (scope, element, attrs) {
        var path;

        attrs.$observe('goClick', function (val) {

            path = val;
        });

        element.bind('click', function () {
            scope.$apply(function () {
                $location.path(path);
            });
        });
    };
});






